import Vue from 'vue'
import store from '../store'
import VueRouter from 'vue-router'
import { Toast } from 'vant'
Vue.use(VueRouter)

const routes = [
  { path: '/', name: 'Home', component: () => import('../views/home') },
  {
    path: '/remove', name: 'Remove', meta: { skip: true }, beforeEnter: (to, from, next) => {
      store.commit('DEL_LOGIN')
      next({ name: 'Login', replace: true })
    }
  },
  {
    path: '/account',
    redirect: '/login',
    component: () => import('../views/account/layout'),
    children: [{ path: '/login', name: 'Login', meta: { skip: true }, component: () => import('../views/account/login') }]
  },
  { path: '*', name: 'All', meta: { skip: true }, redirect: '/remove' }
]

const router = new VueRouter({ routes })
//全局前置守卫
router.beforeEach((to, from, next) => {
  Toast.loading()
  //已登录 或 跳过登录验证
  if (to.meta?.skip || store.state?.accessToken) next()
  else {
    Toast.clear()
    next({ name: 'Login', replace: true, query: { redirect: to.fullPath } })
  }
})
//全局后置钩子
router.afterEach(() => {
  Toast.clear()
})

export default router
